package com.qsl.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * * 假设有三个线程：t1,t2,t3
 * *      t1 打印5次，t2 打印10次，t3 打印15次
 * *      接着 t1 打印5次，t2 打印10次，t3 打印15次
 * *      ...
 * *      一共10轮
 */
public class SyncAndLockDiffDemo {

    public static void main(String[] args) {

        ShareData shareData = new ShareData(3);

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                shareData.print(1, 5);
            }
        }, "t1").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                shareData.print(2, 10);
            }
        }, "t2").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                shareData.print(3, 15);
            }
        }, "t3").start();
    }

    static class ShareData {

        private int threadNums;
        private int num = 1;
        private Lock lock;
        private Map<Integer, Condition> conditionMap;

        public ShareData(int threadNums) {
            this.threadNums = threadNums;
            lock = new ReentrantLock();
            conditionMap = new HashMap<>();
            for (int i = 1; i <= threadNums; i++) {
                conditionMap.put(i, lock.newCondition());
            }
        }

        public void print(int currentThreadNum, int printTimes) {
            lock.lock();
            try {
                while (num != currentThreadNum) {
                    conditionMap.get(currentThreadNum).await();
                }
                for (int i = 1; i <= printTimes; i++) {
                    System.out.println(Thread.currentThread().getName() + " " + i);
                }
                if (++num > threadNums) {
                    num = 1;
                }
                conditionMap.get(num).signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

}
